const url = require("url");
const http = require("http");
const https = require("https");
const querystring = require("querystring");
const paramUtil = require("./paramUtil");

let request = function (req, action, postData, method, headers) {
  let urlObj = url.parse(action, true);
  if (!urlObj || !urlObj.protocol || !urlObj.path) {
    return Promise.reject(`url[${action}] lost protocol`);
  }
  headers = headers || { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" };

  headers = Object.assign({}, headers, {
    "Content-Length": Buffer.byteLength(postData),
    Connection: "keep-alive",
  });

  let options = {
    hostname: urlObj.hostname,
    port: urlObj.port,
    path: urlObj.path,
    method: method || "POST",
    headers: headers,
  };

  return new Promise(function (resolve, reject) {
    let reqCallback = function (res) {
      let bufferArray = [];

      res.on("data", function (chunk) {
        bufferArray.push(chunk);
      });

      res.on("end", function () {
        resolve(Buffer.concat(bufferArray));
      });
    };

    let req = urlObj.protocol.indexOf("https") > -1 ? https.request(options, reqCallback) : http.request(options, reqCallback);

    req.on("error", function (err) {
      reject(err);
    });

    req.write(postData);

    req.end();
  });
};

module.exports = {
  post: function (req, action, params, headers) {
    paramUtil.clearEmptyValue(params);

    return request(req, action, params ? querystring.stringify(params) : "", "POST", headers).then(
      function (value) {
        return value.toString("utf8");
      },
      function (reason) {
        return reason;
      }
    );
  },

  get: function (req, action, params, headers) {
    let queryStr = params ? querystring.stringify(params) : "";

    return request(req, action, queryStr, "GET", headers).then(
      function (value) {
        return value.toString("utf8");
      },
      function (reason) {
        return reason;
      }
    );
  },
};
